package com.hxci.zhongjiahao.tool;

import com.hxci.zhongjiahao.pojo.Course;
import com.hxci.zhongjiahao.servcie.CorseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Configuration
@Component("zhongjiahaoCourseTools")
public class CourseTools {
	@Autowired
	private CorseService corseService;

	public record DeleteCourseDatesRequest(String sno) {}
	public record AddCourseDataRequest(Course course) {}
	public record CourseDetailsRequest(String teacher) {}

	@Bean
	@Description("删除课程")
	public Function<DeleteCourseDatesRequest, String> deleteCourse() {
		return request -> {
			System.out.println("删除课程请求，课程ID: " + request.sno);
			try {
				Integer flag = corseService.del(request.sno);
				if (flag > 0) {
					return "课程删除成功";
				} else {
					return "课程删除失败，请稍后重试";
				}
			} catch (Exception e) {
				return "删除课程时发生错误: " + e.getMessage();
			}
		};
	}

	@Bean
	@Description("添加课程")
	public Function<AddCourseDataRequest, String> addCourse() {
		return request -> {
			System.out.println("添加课程请求: " + request.course);
			try {
				if (request.course.getCname() == null || request.course.getCname().isEmpty()) {
					return "课程名称不能为空";
				}
				if (request.course.getTea() == null || request.course.getTea().isEmpty()) {
					return "任课教师不能为空";
				}
				Integer flag = corseService.save(request.course);
				if (flag > 0) {
					return "课程添加成功";
				} else {
					return "课程添加失败，请稍后重试";
				}
			} catch (Exception e) {
				return "添加课程时发生错误: " + e.getMessage();
			}
		};
	}

	@Bean
	@Description("获取课程")
	public Function<CourseDetailsRequest,List<Course>> getCourseDetails() {
		return request -> {
			System.out.println("查询教师课程请求，教师: " + request.teacher);
			try {
				List<Course> courses = corseService.queryByTeacher(request.teacher);
				return courses;
			} catch (Exception e) {
				System.err.println("查询课程时发生错误: " + e.getMessage());
				return List.of();
			}
		};
	}
}